package com.group5.onlinegame.handler;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.group5.onlinegame.entity.Product;
import com.group5.onlinegame.service.IProductService;
import com.group5.onlinegame.util.ExcelUtil;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("/")
public class ProductHandler {

    @Resource
    private IProductService iProductService;

    @RequestMapping("showProduct")
    @RequiresRoles("good")
    public ModelAndView getProductList(Integer id,@RequestParam(value = "pn",defaultValue = "1")Integer pn){
        ModelAndView modelAndView = new ModelAndView("productList");
        PageHelper.startPage(pn,5);
        List<Product> pList = iProductService.getProductList(id);
        PageInfo page = new PageInfo(pList,5);
        modelAndView.addObject("pageInfo",page);
        return modelAndView;
    }

    //显示弹窗
    @RequestMapping(value = "showProduct2")
    @ResponseBody
    @RequiresRoles("good")
    public List<Product> getProductList2(Integer id){
        List<Product> productList = iProductService.getProductList(id);
        System.out.println(productList);
        return productList;
    }

    //修改商品类型
    @RequestMapping("updateProduct")
    @RequiresRoles("good")
   public String updateProduct(@RequestParam(value = "name")String name,@RequestParam(value = "costGolds")Integer costGolds,
                               @RequestParam(value = "costIngots")Integer costIngots,@RequestParam(value = "photo")String photo,
                               @RequestParam(value = "amount")Integer amount,@RequestParam(value = "saleNum")Integer saleNum,
                               @RequestParam(value = "description")String description,@RequestParam( value = "id")Integer id){
        iProductService.editProduct(name,costGolds,costIngots,photo,amount,saleNum,description,id);
        return "redirect:showProduct";
    }
    //切换商品状态
    @RequestMapping("updateStatus")
    @RequiresRoles("good")
    public String updateStatus(@RequestParam(value = "status")String status,@RequestParam(value = "id")Integer id){
        if(status.equals("1")){
            status = "0";
        }else if (status.equals("0")){
            status = "1";
        }
        iProductService.editStatus(status,id);
        return "redirect:showProduct";
    }

    //增加商品
    @RequestMapping("addProduct")
    @RequiresRoles("good")
    public String addProduct(@Param(value = "typeId")Integer typeId,@Param(value = "name")String name,
                             @Param(value = "costGolds")Integer costGolds, @Param(value = "costIngots")Integer costIngots,
                             @Param(value = "amount")Integer amount,@Param(value = "saleNum")Integer saleNum,
                             @Param(value = "photo")String photo, @Param(value = "description")String description,
                             @Param(value = "isNeedAdress") String isNeedAdress,@Param(value = "status")String status,
                             @Param( value = "id")Integer id){
        iProductService.addProduct(typeId,name,costGolds,costIngots,amount,saleNum,photo,description,isNeedAdress,status,id);
        return "redirect:showProduct";
    }

    //批量删除
    @RequestMapping("delete")
    @ResponseBody
    @RequiresRoles("good")
    public String delete(String ids,Model model){
        System.out.println(ids);
        String[] d = ids.split(",");
        System.out.println("批量删除成功");
        iProductService.deleteMany(d);
        return "ok";
    }

    @RequestMapping("ExportExcel")
    @RequiresRoles("good")
    public void getProductExcel(@RequestParam(value = "id",required = false)Integer id, HttpServletRequest request,HttpServletResponse response){
        List<Product> list = iProductService.getProductExcel(id);
        doExcel(list,request,response);
    }
    private void doExcel(List<Product> list, HttpServletRequest request, HttpServletResponse response){
        String sheetName = "商品信息表";

        //Excel表的表头
        String[] title = new String[]{"商品ID","商品名称","金币单价","元宝单价",
                "库存数量","售出数量","图片地址","商品描述","是否需要地址","状态","商品类型名称"};

        //表格内容用二维数组表示，第一个数组表示单元格的内容，第二个数组代表有多少个单元格
        String[][] values = new String[list.size()][title.length];
        //把数据放入表格
        for(int i = 0;i < list.size();i++){
            Product product = list.get(i);
            values[i][0] = String.valueOf(product.getId());
            values[i][1] = String.valueOf(product.getName());
            values[i][2] = String.valueOf(product.getCostGolds());
            values[i][3] = String.valueOf(product.getCostIngots());
            values[i][4] = String.valueOf(product.getAmount());
            values[i][5] = String.valueOf(product.getSaleNum());
            values[i][6] = String.valueOf(product.getPhoto());
            values[i][7] = String.valueOf(product.getDescription());
            if(product.getIsNeedAdress().equals("1")){
                product.setIsNeedAdress("需要");
            }else {
                product.setIsNeedAdress("不需要");
            }
            values[i][8] = String.valueOf(product.getIsNeedAdress());
            if(product.getStatus().equals("1")){
                product.setStatus("已上架");
            }else {
                product.setStatus("已下架");
            }
            values[i][9] = String.valueOf(product.getStatus());
            values[i][10] = String.valueOf(product.getTypeName());
        }
        //生产Excel表格
        HSSFWorkbook workbook = ExcelUtil.getHSSFWorkbook(sheetName,title,values,null);

        String fileName = "信息表.xls";

        //中文转码
        try {
            fileName = URLEncoder.encode(fileName,"utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition","attachment; filename="+fileName+"");

            ServletOutputStream out = response.getOutputStream();

            workbook.write(out);
            out.flush();
            out.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
